import React, {Component} from 'react'
import {View, Text, ScrollView, StyleSheet, TouchableOpacity} from 'react-native'
import {connect} from 'react-redux'
import * as Progress from 'react-native-progress'

var Sound = require('react-native-sound')
Sound.setCategory('Playback')

class ChallengerReport extends Component {
    static navigationOptions = ({ navigation }) => {
        return {
            headerRight: <View />
        }
    }
    
    constructor(props) {
        super(props)
        this.state = {
            dataForReport: props.navigation.state.params.dataForReport,
            playingIndex: 0,
            voiceProgress: 0,
            playing: false,
            voiceLength: 0
        }
    }

    componentWillUnmount () {
        if (this.voice != undefined) {
            this.voice.stop()
            this.voice.release()
        }
    }


    //获取文字颜色
    getWordColor = (score) => {
        const {score_weighting} = this.props.user.settings
        let color
                            
        if (score >= score_weighting.good) {
            color = 'blue'
        } else if (score >= score_weighting.poor && score < score_weighting.good) {
            color = 'red'
        } else {
            color = 'gray'
        }

        return color
    }
    

    sentenceLabel = (data, index) => {
        return (
            <View key={index} style={{backgroundColor: 'white', padding: 10, borderBottomWidth: 0.3}}>
                <View style={{flexDirection: 'row', flex: 1}}>
                    <View style={{flex: 1, flexDirection: 'row'}}>
                        {
                            data.ibmSentences.map((ibmSentence, i) => {
                                return (
                                    <View key={i}>
                                        <Text style={[styles.word_container, {color: this.getWordColor(ibmSentence.score)}]}>
                                            {ibmSentence.word + " "}
                                        </Text>
                                    </View>  
                                )
                            })
                        }
                    </View>
                    <View style={styles.score_container}>
                        <Text style={{color: 'white'}}>
                            {data.score}
                        </Text>  
                    </View>
                </View>
                {
                    index == this.state.playingIndex && this.state.playing ? 
                    <View style={{marginTop: 10}}>
                        <Progress.Bar progress={this.state.voiceProgress} width={null} borderWidth={0.1} height={3}/>
                    </View> :
                    null
                }
            </View>
        )
    }

     //判断音频是否加载完成
     soundLoaded = () => {
        if (this.voice == undefined) return false
        return this.voice.isLoaded()
    }

     //播放录音
    play = () => {
        Sound.setCategory('Playback')
        //this.setState({soundLoaded: true})
        this.voice.play((success) => {
              //设置一个轮询使进度条改变
            if (success) {
                clearInterval(this.loop_get_time)
                this.voice.release()
                this.voice = undefined
                this.setState({voiceProgress: 0, playing: false})
                let {dataForReport, playingIndex} = this.state
                if (dataForReport[playingIndex + 1] != undefined) {
                    this.state.playingIndex += 1
                    this.onPlay()
                } else {
                    this.setState({
                        playing: false,
                        playingIndex: 0
                    })
                }
                
            } 
        });
        this.loop_get_time = setInterval(() => {
            this.voice.getCurrentTime((sec) => {
                this.setState({voiceProgress: (sec / this.state.voiceLength)})
            })
        }, 100)
    }

    onPlay = () => {
        if (this.state.playing) {
            this.setState({playing: false})
            clearInterval(this.loop_get_time)
            this.voice.pause()
        } else {
            this.setState({playing: true})
            if (this.soundLoaded()) {
                this.play()
            } else {
                let {dataForReport, playingIndex} = this.state
                let currentUrl = dataForReport[playingIndex].playbackUrl
                this.voice = new Sound(currentUrl, '', (error) => {
                    if (error) {
                        //console.log(error, 'error')
                        this.setState({playing: false})
                        return;
                    }
                    this.state.voiceLength = this.voice.getDuration()
                    this.play()
                });
            }
        
        }
    }

    render () {
        return(
            <View style={{flex: 1}}>
                <ScrollView style={{flex: 1}}>
                    {
                        this.state.dataForReport.map((d, index) => {
                            return this.sentenceLabel(d, index)
                        })
                    }
                </ScrollView>
                <View style={styles.play_button_container}>
                    <TouchableOpacity style={styles.play_button} onPress={this.onPlay}>
                        <Text style={{fontSize: 15, color: '#00BBFF'}}>
                            {this.state.playing ? '暂停' : '播放录音'}
                        </Text>
                    </TouchableOpacity>
                </View>
            </View>
        )
    }
}

const styles = StyleSheet.create({
    score_container: {
        backgroundColor: 'orange', 
        alignItems: 'center', 
        justifyContent: 'center', 
        borderRadius: 5, 
        padding: 4, 
        margin: 10
    },

    word_container: {
        fontSize: 20,
        justifyContent: 'flex-start',
        alignItems: 'flex-start'
    },

    play_button_container: {
        margin: 10,
        padding: 10, 
        backgroundColor: 'white',
        justifyContent: 'center',
        alignItems: 'center',
        height: 50
    },

    play_button: {
        borderRadius: 15, 
        borderColor: '#00BBFF', 
        padding: 5, 
        flex: 1, 
        borderWidth: 0.3
    }
})

const mapStateToProps = (state) => {
    return {
       user: state.user
    }
}

export default connect(mapStateToProps)(ChallengerReport)